﻿/*========================== 
 * @author 郑金泉
 * @desc 实体基因信息类? (通过该类信息可生产对应实体对象)
 * ========================= */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Obsidian.Config;
using Obsidian.Data.Sql;

namespace Obsidian.Edm
{
    public class ModelGene
    {

        private static Dictionary<string, Type> dictModeTypes = new Dictionary<string, Type>();

        private string dbAlias;
        private string tableAlias;
        private Type modelType;

        public ModelGene(string dbAlias, string tableAlias)
        {
            this.dbAlias = dbAlias;
            this.tableAlias = tableAlias;
            Type type = GetModelType(dbAlias, tableAlias);
            if (type == null)
                throw new Exception(String.Format("未能找到{0}.{1}对应的类型", dbAlias, tableAlias));
            this.modelType = type;
        }

        public string DbAlias
        {
            get { return dbAlias; }
        }

        public string TableAlias
        {
            get { return tableAlias; }
        }

        public Type ModelType
        {
            get { return this.modelType; }
        }

        public object CreateModel()
        {
            return Activator.CreateInstance(this.modelType);
        }

        public static Type GetModelType(string dbAlias, string tableAlias)
        {
            ModelConfig.ModelPackageInfo pkgInfo = ModelConfig.GetModelPackageInfo(dbAlias, tableAlias);

            if (pkgInfo == null)
                return null;
            if (pkgInfo.CheckForChanged())
            {
                lock (dictModeTypes)
                {
                    dictModeTypes.Clear();
                    Assembly assembly = Assembly.LoadFrom(pkgInfo.AssemblyFile);
                    foreach (ModelConfig.ModelInfo modelInfo in pkgInfo.ModelInfos)
                    {
                        Type t = assembly.GetType(modelInfo.Type, false);
                        if (t == null)
                            throw new Exception("找不到Model类型：" + modelInfo.Type);
                        dictModeTypes.Add(modelInfo.Alias, t);
                    }
                }
            }
            Type modelType;
            if (dictModeTypes.TryGetValue(tableAlias, out modelType))
                return modelType;
            else
                return null;
        }

    }
}
